<?php


namespace app\admin\controller;

use app\admin\model\Device as DeviceModel;

/***
 * 设备管理控制器
 * Class Device
 * @package app\admin\controller
 */
class Device extends Base
{
    /***
     * 展示页面
     */
    public function lists() {
        return $this->fetch();
    }

    /***
     * layui 数据表格接口
     */
    public function get_device_list() {
        $device = new DeviceModel();
        //排除被删除的
//        $this->_condition['where']['deleted'] = 0;
//        $this->_condition['with'] = 'user';
        $data = $device->get_data_list($this->_condition);
        for ($i = 0; $i < count($data); $i++) {
            if (is_null($data[$i]['user_id'])) {
                $data[$i]['nick_name'] = '';
            } else {
                $data[$i]['nick_name'] = $data[$i]->user->nick_name;
            }
        }
        $count = $device->get_data_count($this->_condition['where']);
//        echo $this->_condition['where'];
//        die();
        response_json('', $data, $count);
    }


    /***
     * Desc:生成二维码
     * User: HAIYUN
     * Date: 2022/2/27 14:59
     */
    public function cerate_qrcode($comment) {
        vendor('qrcode/phpqrcode');//引入类库
        $value                = $comment;         //二维码内容
        $errorCorrectionLevel = 'L';  //容错级别
        $matrixPointSize      = 5;      //生成图片大小
        //生成二维码图片
        // 判断是否有这个文件夹  没有的话就创建一个
        if (!is_dir("image/qrcode")) {
            // 创建文件加
            mkdir("image/qrcode");
        }
        //设置二维码文件名
        $filename = 'image/qrcode/' . time() . rand(10000, 9999999) . '.png';
        //生成二维码
        \QRcode::png($value, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
        //如果需要转换成base64数据，解开下面这行注释即可
        //$image_data = chunk_split(base64_encode(fread(fopen($filename, 'r'), filesize($filename))));
        //获取当前域名
        $domain  = $this->request->domain();
        return $domain . '/' . $filename;
    }

    public function add() {
        return $this->_edit();
    }

    public function edit($id) {
        return $this->_edit($id);
    }

    /***
     * Desc:通用新增修改
     * User: HAIYUN
     * Date: 2022/2/27 15:39
     * @param string $id
     */
    public function _edit($id = '') {
        $device = new DeviceModel();
        if($this->request->isPost()){
            $this->check_authority();
            $rules = [
                ['device_number','require|length:3,16|unique:device','昵称不能为空|设备号长度应在2~16个字符之间|该设备已存在'],
                ['address','require','地址不能为空'],
            ];
            $msg = $this->validate($this->_param,$rules);
            if($msg !== true) $this->error($msg, '');
            //生成二维码(跳转至设备开关锁页面)
            $comment = "http://localhost:18800/index.php/device/operateDevice?device_number=" . $this->_param['device_number'];
            $this->_param['qrcode'] = $this->cerate_qrcode($comment);
            if($id){
                $res = $device->edit($this->_param,['id'=>$this->_param['id']]);
            }else{
                $res = $device->add($this->_param);
            }
            if($res !== false){
                $str = empty($id) ? '添加设备: ' : '修改设备';
                log_write( $str . $this->_param['device_number'],$device->getLastSql());
                $this->success(empty($id) ? '添加设备成功!' : '修改设备成功', url('lists'));
            }else{
                $this->error($device->getError(), '');
            }
        }
        if($id){
            $info = $device->where('id',$id)->find();
            $this->assign('info',$info);
        }
        return $this->fetch('edit');
    }

    /***
     * Desc :单个删除
     * User : HAIYUN
     * Date : 2022-01-11 15:44
     */
    public function del()
    {
        $this->check_authority();
        if (!isset($this->_param['id']) || !isset($this->_param['device_numbers']))
            $this->error('参数错误');
        $device = new DeviceModel();
        $res     = $device->del(['id' => ['in', $this->_param['id']]]);
        if (!$res) {
            $this->error('删除失败!');
        } else {
            //写入操作日志
            if (is_array($this->_param['device_numbers']))
                $this->_param['device_numbers'] = implode(',', $this->_param['device_numbers']);
            log_write('删除设备:' . $this->_param['device_numbers'], $device->getLastSql());
            $this->success('删除成功!', 'lists');
        }

    }

    /***
     * 修改状态
     */
    public function change_status()
    {
        $this->check_authority();
        if (!isset($this->_param['id']) || !isset($this->_param['status']))
            $this->error('参数错误');
        $device = new DeviceModel();
        $res     = $device->edit(['status' => $this->_param['status']], ['id' => $this->_param['id']]);
        if (!$res) {
            $this->error($this->_param['status'] == 0 ? '禁用失败' : '启用失败');
        } else {
            $str = $this->_param['status'] == 0 ? '禁用' : '启用';
            log_write($str . '设备号:' . $this->_param['name'], $device->getLastSql());
            $this->success($this->_param['status'] == 0 ? '禁用成功' : '启用成功', 'lists');
        }
    }
}